package feed

import (
	"encoding/json"
	"os"

	"code.google.com/awwwe-browser/auralvm/param"
	"code.google.com/awwwe-browser/data"
	"code.google.com/awwwe-browser/slurp"
)

var feedKeyer int = 0

type Feed struct {
	Key      int
	Host     string
	SiteName string
	URL      string
}

func BuildFeed() Feed {
	var v Feed
	v.Key = feedKeyer
	feedKeyer++
	return v
}

func CountFeeds() int {
	var feeds SliceFeed
	feeds = UnMarshalFeeds()
	return feeds.Len()
}

// a feed slice
type SliceFeed struct {
	data.SlicerBase
}

// a cmp method for feeds
func cmpFeed(i1 interface{}, i2 interface{}) int {
	if i1.(*Feed).Key == i2.(*Feed).Key {
		return 0
	}
    return -1
}

// Builds a feed slice.
// Param length is the start length of the array's slice
// Param capacity is the size of the slice's array
//
// example:
//  var ss SliceFeed
//  ss = BuildSliceFeed(0, 5)
func BuildSliceFeed(length, capacity int) SliceFeed {
	var v SliceFeed
	v.Init(length, capacity, cmpFeed)
	return v
}

// Returns the slice's element at the slice's index.
// Param index is the index of the slice.
func (this *SliceFeed) AtIndex(index int) *Feed {
	var ifc interface{}
    ifc = this.SlicerBase.AtIndex(index)
    if ifc != nil {
        return ifc.(*Feed)
    } else {
        return nil
    }
}

// Remove gets an item at index
// Deletes the item at index form the array
// Returns the item.
func (this *SliceFeed) Remove(index int) *Feed {
	var ifc interface{}
	ifc = this.SlicerBase.Remove(index)
    if ifc != nil {
		return ifc.(*Feed)
    }
    return nil
}

// Returns the data as a slice.
func (this *SliceFeed) Slice() []*Feed {
	var i, length int
	var item interface{}
	var ss []*Feed
	length = len(this.Data)
	ss = make([]*Feed, length, length)
	for i, item = range this.Data {
		ss[i] = item.(*Feed)
	}
	return ss
}

// Appends a feed to the slice as a pointer.
func (this *SliceFeed) Append(src *Feed) {
    this.SlicerBase.Append(src)
}

// Appends a slice of feeds to the slice.
func (this *SliceFeed) AppendSlice(src []Feed) {
	var v Feed
    for _, v = range src {
    	this.Append(&v)
    }
}

func (this *SliceFeed) Marshal() error {
	var markup []byte
	var err error
	var file *os.File
	markup, err = json.MarshalIndent(this.Slice(), "", "  ")
	if err == nil {
		file, err = os.Create(param.LocalFeedFilePath)
		defer file.Close()
		if err == nil {
			_, err = file.Write(markup)
		}
	}
	return err
}

func UnMarshalFeeds() SliceFeed {
	var slicef SliceFeed
	var feeds []Feed
	var markup []byte
	var err error
	feeds = make([]Feed, 0, 5)
	slicef = BuildSliceFeed(0, 20)
	markup, err = slurp.SlurpFile(param.LocalFeedFilePath)
	if err == nil {
		err = json.Unmarshal(markup, &feeds)
		if err == nil {
			slicef.AppendSlice(feeds)
		}
	}
	return slicef
}
